import React, { useEffect, useState } from 'react';
import { Card, Row, Col, DatePicker, Spin, Empty, Alert } from 'antd';
import { Column } from '@ant-design/charts';
import axios from 'axios';
import dayjs from 'dayjs';
import type { Dayjs } from 'dayjs';
import isBetween from 'dayjs/plugin/isBetween';
import isSameOrBefore from 'dayjs/plugin/isSameOrBefore';

// 扩展dayjs
dayjs.extend(isBetween);
dayjs.extend(isSameOrBefore);

const { RangePicker } = DatePicker;

interface PurchaseData {
  transaction_id: string;
  product_id: string;
  purchase_date: string;
  status: string;
}

interface DailyStats {
  date: string;
  count: number;
  product: string;
}

interface PurchaseChartsProps {
  token: string;
}

const PurchaseCharts: React.FC<PurchaseChartsProps> = ({ token }) => {
  const [loading, setLoading] = useState(false);
  const [purchaseData, setPurchaseData] = useState<PurchaseData[]>([]);
  const [dailyStats, setDailyStats] = useState<DailyStats[]>([]);
  const [dateRange, setDateRange] = useState<[Dayjs, Dayjs]>([
    dayjs().subtract(30, 'days'),
    dayjs()
  ]);
  const [error, setError] = useState<string | null>(null);

  // 处理日期范围变化
  const handleDateRangeChange = (dates: any) => {
    if (dates && Array.isArray(dates) && dates.length === 2) {
      setDateRange([dates[0], dates[1]]);
    }
  };

  // 获取购买数据
  useEffect(() => {
    const fetchData = async () => {
      setLoading(true);
      setError(null);
      try {
        const response = await axios.get('/api/purchases', {
          headers: {
            'Authorization': `Bearer ${token}`,
            'Content-Type': 'application/json',
          },
        });
        
        if (response.data) {
          setPurchaseData(response.data);
        } else {
          setError('返回数据格式不正确');
        }
      } catch (error: any) {
        console.error('图表数据请求错误:', error);
        setError(error.response?.data?.error || '获取数据失败');
      } finally {
        setLoading(false);
      }
    };

    if (token) {
      fetchData();
    }
  }, [token]);

  // 处理数据并生成图表数据
  useEffect(() => {
    if (purchaseData.length > 0 && dateRange.length === 2) {
      const startDate = dateRange[0].startOf('day');
      const endDate = dateRange[1].endOf('day');
      
      // 过滤指定日期范围内的数据
      const filteredData = purchaseData.filter(item => {
        const purchaseDate = dayjs(item.purchase_date);
        return purchaseDate.isAfter(startDate) && 
               purchaseDate.isBefore(endDate) && 
               item.status === 'purchased';
      });
      
      // 获取唯一的产品ID列表
      const uniqueProductIds = Array.from(new Set(filteredData.map(item => item.product_id)));
      
      // 按日期和产品分组统计
      const dailyMap = new Map();
      
      filteredData.forEach(item => {
        const dateStr = dayjs(item.purchase_date).format('YYYY-MM-DD');
        const product = item.product_id;
        const key = `${dateStr}-${product}`;
        
        if (dailyMap.has(key)) {
          dailyMap.set(key, dailyMap.get(key) + 1);
        } else {
          dailyMap.set(key, 1);
        }
      });
      
      // 转换为图表数据格式
      const stats: DailyStats[] = [];
      
      // 生成日期范围内的所有日期
      let currentDate = startDate.clone();
      const dates: string[] = [];
      
      while (currentDate.isBefore(endDate) || currentDate.isSame(endDate, 'day')) {
        dates.push(currentDate.format('YYYY-MM-DD'));
        currentDate = dayjs(currentDate.add(1, 'day').valueOf());
      }
      
      // 为每个日期和产品生成数据点
      dates.forEach(dateStr => {
        uniqueProductIds.forEach(productId => {
          const key = `${dateStr}-${productId}`;
          const count = dailyMap.has(key) ? dailyMap.get(key) : 0;
          
          stats.push({
            date: dateStr,
            count: count,
            product: productId
          });
        });
      });
      
      setDailyStats(stats);
    }
  }, [purchaseData, dateRange]);

  const columnConfig = {
    data: dailyStats,
    isGroup: true,
    xField: 'date',
    yField: 'count',
    seriesField: 'product',
    columnWidthRatio: 0.6,
    label: {
      // 不显示数值标签，以保持图表整洁
      position: 'middle',
      style: {
        fill: '#FFFFFF',
        opacity: 0.6,
      },
      // 只在数值大于0时显示标签
      content: (item: any) => (item.count > 0 ? item.count : ''),
    },
    xAxis: {
      label: {
        autoHide: true,
        autoRotate: true,
      },
      title: {
        text: '日期'
      },
      tickCount: 5, // 减少X轴标签数量以避免拥挤
    },
    yAxis: {
      title: {
        text: '购买数量'
      }
    },
    meta: {
      date: {
        alias: '日期',
      },
      count: {
        alias: '购买数量',
      },
      product: {
        alias: '产品类型'
      }
    },
    color: ['#1890ff', '#52c41a', '#fa8c16', '#f5222d', '#722ed1'],
    interactions: [{ type: 'element-active' }],
    legend: {
      position: 'top-right',
    }
  };

  return (
    <Card 
      title="产品购买统计" 
      extra={
        <RangePicker 
          value={dateRange}
          onChange={handleDateRangeChange}
          allowClear={false}
        />
      }
      className="chart-card"
    >
      {error && <Alert message={error} type="error" showIcon style={{ marginBottom: 16 }} />}
      
      <Spin spinning={loading}>
        {dailyStats.length > 0 ? (
          <Row gutter={[16, 16]}>
            <Col span={24}>
              <Column {...columnConfig} height={300} />
            </Col>
          </Row>
        ) : (
          <Empty description="暂无数据" />
        )}
      </Spin>
    </Card>
  );
};

export default PurchaseCharts; 